import logging

import  requests
import  json
from  urllib import  parse
import hashlib
import  base64
import  rsa
from  django.core.exceptions import ValidationError
#appid获取参考 https://e-cloudstore.com/doc.html?appId=af09c25938714c26b9736f535ca20fc9
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA





appid = "1721923452"
# 50秒
token_time = "50"
#"私钥"
secrit = "70f663a1-a42a-437c-9da1-84de3feef7cb",
#公钥
spk = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv/Sn2oHPPPztKqRmvQwdy6nBaIbjbv/2b0mjc3ZPnCRmsoHj79g9GwkkYDuFAkc8W6OvO0m7isfe6c+kWyL3A4HfMWdB9/adj27Iss9SjpVo/L+sGq2aQ4G/rCu1i12MXk2Rz4fVnkP/wVZ47p3pH5haSaCo76LYhkBiOTCnjwWafa0Mwl1I2hQ8/M0BMuZXla46LCyasGKVEtpuwgTeHwlsdh+6w4vBnYBvZf2L7/Pq5RYCBx9s6BLQ4Y2az5m+NDE1Dn7A3bBIjrS7Ok4IdoXahxfjd09fGUqIuYvsmnjVzX9K1h59DJxd+L+KHBRo81FZKLEHCegEi7oe9ea85wIDAQAB"
secret = "fNARKu0WBON1Zo7V01Vgx/MNgUVWnUMhJgOm2ZEYBzVDCvgnLMfVVFdoYRdwSSlNS+QKQDTP8RRy3IIYH4Yj0KzokRUaC6h29Pe2jU+DTRTyLZWelGXHH61y60Xna3NRZgaMwefNxq7AQ15fLE8NxKQe+J44QA5t83wMmECDRvNHD88MIv5RXi4hkloJbK/pOrozbNmiYk4D2JOgQpdNwqSyKwn4oeikLoEg4qTnN+yze+YwmZ3URJknKj3YE6+Py+7XS+m/ozpHwELq2s7dFH5jsq5MTvcezN9a/tXFohz33nGpCztEuKcAxYsPcoZFV8KcR2iC2oIfkSAnugbs/g=="
oa_url = "https://172.19.234.52:8090"
token_api = r"/api/ec/dev/auth/applytoken"

#建模后台>接口管理创建>创建/更新数据
create_api = r"/api/cube/restful/interface/saveOrUpdateModeData/create"
#查询  条件查询返回数据的数量
select_api = r"/api/cube/restful/interface/getDataByPK/sd"
systemid =  "test"
password = "3dmed123!"
public_key_pem = """-----BEGIN PUBLIC KEY-----
                 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv/Sn2oHPPPztKqRmvQwd
                 y6nBaIbjbv/2b0mjc3ZPnCRmsoHj79g9GwkkYDuFAkc8W6OvO0m7isfe6c+kWyL3
                 A4HfMWdB9/adj27Iss9SjpVo/L+sGq2aQ4G/rCu1i12MXk2Rz4fVnkP/wVZ47p3p
                 H5haSaCo76LYhkBiOTCnjwWafa0Mwl1I2hQ8/M0BMuZXla46LCyasGKVEtpuwgTe
                 Hwlsdh+6w4vBnYBvZf2L7/Pq5RYCBx9s6BLQ4Y2az5m+NDE1Dn7A3bBIjrS7Ok4I
                 doXahxfjd09fGUqIuYvsmnjVzX9K1h59DJxd+L+KHBRo81FZKLEHCegEi7oe9ea8
                 5wIDAQAB
                 -----END PUBLIC KEY-----"""

logger = logging.getLogger(__name__)
# RSA包的
public_key = public_key_pem.encode('utf-8')
public_obj = rsa.PublicKey.load_pkcs1_openssl_pem(public_key)
#token 信号, 获取过token后就等于1，创建接口使用后变回0
#存储token
token_con = None

def get_token():
    global  token_con
    headers = {
        "appid" : appid,
        "time" : token_time,
        "secret" : secret
    }
    response = requests.post(url=oa_url+token_api,headers=headers,verify = False)
    if response.status_code == 200:

        token_con = json.loads(response.text)['token']
        logger.info("OA系统token请求成功,继续业务接口请求")
        return  json.loads(response.text)['token']
    else:
        logger.error("token请求失败")
        logger.error(response.status_code)
        logger.error(response.status_code)
        raise ValidationError("token请求失败")

#创建 公共参数 Md5
def create_md5(currentDateTime:str):
    string = systemid + password + str(currentDateTime)
    #加密 string
    md5 = hashlib.md5()
    md5.update(string.encode('utf - 8'))
    return  md5.hexdigest()

#创建 请求头中的参数 RSA加密的userID
def create_rsa_userid(userid):
    #修改编码
    encode_userid = userid.encode('utf-8')
    # 加密
    rsa_userid = rsa.encrypt(encode_userid, public_obj)
    # 修改成base64编码
    encode_rsa_userid = base64.b64encode(rsa_userid)
    return  encode_rsa_userid.decode()

#创建数据
def create_formdata(data,userid,currentDateTime):
    global  token_con

    if token_con:
        logger.info("使用已存在的token执行创建任务")
        token = token_con
    else:
        token  = get_token()
        logger.info("token过期重新获取")
    header= {
        "token" : token,
        "appid" : appid,
        "userid" : create_rsa_userid(userid),
        "Content-Type" : "application/x-www-form-urlencoded; charset=utf-8"
    }

    request_data = {
        "datajson" : {
            "data" : [
                {
                    "operationinfo": {
                        "operator": str(userid),
                    },
                    "mainTable": data
                },
            ],
            "header" : {
                "systemid": systemid,
                "currentDateTime": currentDateTime,
                "Md5": create_md5(str(currentDateTime))
            }
        }
}
    #将body转换成 x_www_form_urlencoded
    x_www_form_urlencoded_data = parse.urlencode(request_data).encode("utf-8")

    response = requests.post(url=oa_url+create_api,data=x_www_form_urlencoded_data,headers=header,verify = False)
    if response.status_code == 200:
        #初始化token容器
        token_con = None
        logger.info("数据创建成功")

#查询是否此发票号码已存在
def select_fphm_isExist(userid,data,currentDateTime):

    header = {
        "token": get_token(),
        "appid": appid,
        "userid": create_rsa_userid(userid),
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
    }

    request_data = {
        "datajson": {
                    "operationinfo": {
                        "operator": str(userid),
                    },
                    "mainTable": data,

            "header": {
                "systemid": systemid,
                "currentDateTime": currentDateTime,
                "Md5": create_md5(str(currentDateTime))
            }
        }
    }
    # 将body转换成 x_www_form_urlencoded
    x_www_form_urlencoded_data = parse.urlencode(request_data).encode("utf-8")

    response = requests.post(url=oa_url + select_api, data=x_www_form_urlencoded_data, headers=header,verify = False)
    if response:
        json_res = json.loads(response.text)
        if json_res['result'] != '{}':
            logger.error('发票号码'+data['fphm']+"重复录入")
            logger.error(json_res)

            raise Exception("发票重复录入！")
        else:
            print("未查询到次发票可以创建:"+data['fphm'])
            print(response.text)
            logger.info("未查询到次发票可以创建:"+data['fphm'])
    else:
        logger.error("发送给OA的查询发票号码接口未得到回应,response为空！")
        raise  Exception("未接受到OA的回应")
